# # 超市购物系统业务需求
# # 基于列表技术的购物程序
#
# def main():
#     # 使用列表存储商品信息（元组列表：(商品名, 价格)）
#     products = [
#         ("苹果", 8.5),
#         ("香蕉", 5.0),
#         ("牛奶", 6.8),
#         ("面包", 12.0),
#         ("鸡蛋", 15.8),
#         ("洗发水", 45.0),
#         ("牙膏", 12.5),
#         ("笔记本", 3.0)
#     ]
#
#     # 1. 用户账户余额
#     user_money = 1000.0  # 初始金额1000元
#
#     # 2. 空购物车（列表存储购买的商品：(商品名, 价格, 数量)）
#     shopping_cart = []
#
#     print("=" * 40)
#     print("欢迎来到便民超市！")
#     print(f"您的初始余额: ¥{user_money:.2f}")
#     print("商场商品列表:")
#     # 使用enumerate遍历列表，获取索引和元素
#     for i, (product, price) in enumerate(products, 1):
#         print(f"  {i}. {product}: ¥{price:.2f}")
#     print("=" * 40)
#     print("请输入商品编号或名称开始购物，输入'Q'或'q'结束购物")
#
#     while True:
#         # 获取用户输入
#         choice = input("\n请输入要购买的商品编号或名称: ").strip()
#
#         # 检查是否退出
#         if choice.lower() == 'q':
#             break
#
#         # 查找商品（支持编号或名称）预先设置为找到的初值，方便后面更新
#         found = False
#         product_name = ""
#         product_price = 0.0
#
#         if choice.isdigit():  # 判断是否为数字（编号）
#             index = int(choice) - 1
#             if 0 <= index < len(products):
#                 product_name, product_price = products[index]
#                 found = True
#                 print(f"你选择了: {products[index]}")
#             else:
#                 print("无效的商品编号")
#         else:  # 处理商品名称
#             for name, price in products:
#                 if name == choice:
#                     product_name, product_price = name, price
#                     found = True
#                     break
#
#         # 处理查找结果
#         if not found:
#             print("没有这个商品，别瞎弄！")
#             continue
#         # 检查余额是否足够
#         if user_money >= product_price:
#             # 检查购物车中是否已有该商品
#             in_cart = False
#             for i in range(len(shopping_cart)):
#                 # 列表元素访问和修改
#                 if shopping_cart[i][0] == product_name:
#                     # 数量加1
#                     shopping_cart[i] = (product_name, product_price, shopping_cart[i][2] + 1)
#                     in_cart = True
#                     break
#
#             # 如果不在购物车中，添加新商品（列表追加）
#             if not in_cart:
#                 shopping_cart.append((product_name, product_price, 1))
#
#             # 扣减余额
#             user_money -= product_price
#             print(f"恭喜，购买成功！{product_name}已加入购物车")
#             print(f"您的卡余额还剩: ¥{user_money:.2f}")
#         else:
#             print(f"穷鬼，钱不够！{product_name}需要¥{product_price:.2f}，您只有¥{user_money:.2f}")
#             print("请到其他超市购买！")
#
#     # 打印购物小条（购物后处理）
#     print("\n" + "=" * 40)
#     print("              购物小条")
#     print("=" * 40)
#     print(f"购物时间: {time.ctime()}")  # 显示当前时间
#     print("-" * 40)
#     print(f"{'商品名称':<10} {'单价(元)':<10} {'数量':<5} {'小计(元)':<10}")
#     print("-" * 40)
#
#     total = 0.0
#     # 遍历购物车计算总价
#     for item in shopping_cart:
#         name, price, quantity = item
#         subtotal = price * quantity
#         total += subtotal
#         print(f"{name:<12} {price:<10.2f} {quantity:<5} {subtotal:<10.2f}")
#
#     print("-" * 40)
#     print(f"总计: ¥{total:.2f}")
#     print(f"实付: ¥{total:.2f}")
#     print(f"余额: ¥{user_money:.2f}")
#     print("=" * 40)
#     print("感谢您的光临，欢迎下次再来！")
#
#
# if __name__ == "__main__":
#     import time  # 导入时间模块用于显示购物时间
#     main()





# 购物系统业务需求V2.0
# 增强版购物程序（含优惠券和退货功能）

import random
import time


def main():
    # 商品列表（元组列表：(商品名, 价格)）
    products = [
        ("苹果", 8.5),
        ("香蕉", 5.0),
        ("牛奶", 6.8),
        ("面包", 12.0),
        ("鸡蛋", 15.8),
        ("洗发水", 45.0),
        ("牙膏", 12.5),
        ("笔记本", 3.0),
        ("空调", 2999.0),  # 新增空调商品用于演示优惠券
        ("手机", 3999.0)
    ]

    # 1. 生成10张优惠券并随机抽取一张
    coupons = [
        ("苹果", 0.9), ("香蕉", 0.85), ("牛奶", 0.95),
        ("面包", 0.8), ("鸡蛋", 0.9), ("洗发水", 0.75),
        ("牙膏", 0.8), ("笔记本", 0.9), ("空调", 0.8),
        ("无门槛", 0.98)  # 无门槛优惠券对所有商品有效
    ]
    selected_coupon = random.choice(coupons)
    coupon_product, coupon_discount = selected_coupon

    # 2. 用户账户余额
    user_money = 10000.0  # 初始金额提高以支持高价商品

    # 3. 空购物车（列表存储购买的商品：(商品名, 原价, 数量, 折扣价)）
    shopping_cart = []

    # 欢迎信息与优惠券展示
    print("=" * 60)
    print("🎉 欢迎来到便民超市！🎉")
    print(f"💰 您的初始余额: ¥{user_money:.2f}")
    print(f"🎁 您抽到的优惠券: {coupon_product} {int(coupon_discount * 10)}折")
    print("=" * 60)
    print("商场商品列表:")
    for i, (product, price) in enumerate(products,1):
        print(f"  {i}. {product}: ¥{price:.2f}")
    print("=" * 60)
    print("操作指南:")
    print("  - 输入商品编号或名称添加到购物车")
    print("  - 输入'T'或't'查看购物车并可选择退货")
    print("  - 输入'Q'或'q'结束购物并结算")

    while True:
        # 获取用户输入
        choice = input("\n请输入操作(商品编号/名称/T/q): ").strip()

        # 检查是否退出
        if choice.lower() == 'q':
            break

        # 查看购物车与退货功能
        if choice.lower() == 't':
            if not shopping_cart:
                print("您的购物车是空的，没有可退货的商品！")
                continue

            print("\n🛒 您的购物车:")
            print("-" * 50)
            print(f"{'序号':<5} {'商品名称':<10} {'单价(元)':<10} {'数量':<4} {'折扣价(元)':<9}")
            print("-" * 50)
            for i, item in enumerate(shopping_cart, 1):
                name, original_price, quantity, discount_price = item
                print(f"{i:<7} {name:<12} {original_price:<10.2f} {quantity:<5} {discount_price:<10.2f}")

            # return_choice = input("\n请输入要退货的商品序号(按回车取消): ").strip()
            while True:
                return_choice = input("\n请输入要退货的商品序号(按回车取消): ").strip()
                if not return_choice:
                    print("已取消退货操作")
                    break
                if return_choice.isdigit():
                # try:
                    return_index = int(return_choice) - 1
                    if 0 <= return_index < len(shopping_cart):
                        # 从购物车移除商品
                        returned_item = shopping_cart.pop(return_index)
                        name, original_price, quantity, discount_price = returned_item
                        # 退还金额
                        user_money += discount_price * quantity
                        print(f"已成功退货: {name} x{quantity}，退款¥{discount_price * quantity:.2f}")
                        print(f"当前余额: ¥{user_money:.2f}")
                        break
                else:
                    print("无效的序号，请重新输入！")
                # except ValueError:
                #     print("请输入有效的数字序号！")
            continue
        # 查找商品（支持编号或名称）
        found = False
        product_name = ""
        product_price = 0.0

        # 先尝试按编号查找
        # try:
        if choice.isdigit():
          index = int(choice) - 1
          if 0 <= index < len(products):
            product_name, product_price = products[index]
            found = True
          else:
            print("无效的商品编号")
        # except ValueError:
            # 按名称查找
        else:
         for name, price in products:
            if name == choice:
             product_name, product_price = name, price
             found = True
            break

        # 处理查找结果
        if not found:
            print("❌ 没有这个商品，请重新输入！")
            continue

        # 计算折扣价
        if coupon_product == "无门槛" or coupon_product == product_name:
            discount_price = product_price * coupon_discount
            discount_info = f"（使用{int(coupon_discount * 10)}折优惠券）"
        else:
            discount_price = product_price
            discount_info = ""

        # 检查余额是否足够
        if user_money >= discount_price:
            # 检查购物车中是否已有该商品
            in_cart = False
            for i in range(len(shopping_cart)):
                if shopping_cart[i][0] == product_name:
                    # 数量加1
                    name, original, qty, disc = shopping_cart[i]
                    shopping_cart[i] = (name, original, qty + 1, disc)
                    in_cart = True
                    break

            # 不在购物车中则添加
            if not in_cart:
                shopping_cart.append((product_name, product_price, 1, discount_price))

            # 扣减余额
            user_money -= discount_price
            print(f"✅ 购买成功！{product_name}已加入购物车 {discount_info}")
            print(f"当前余额: ¥{user_money:.2f}")
        else:
            print(f"❌ 余额不足！{product_name}需要¥{discount_price:.2f}，您当前余额¥{user_money:.2f}")

    # 打印优化后的购物小条
    print("\n" + "=" * 60)
    print("                      购物小条")
    print("=" * 60)

    print(f"购物时间: {time.strftime('%Y年%m月%d日 %H:%M:%S')}")
    print(f"使用优惠券: {coupon_product} {int(coupon_discount * 10)}折")
    print("-" * 60)
    print(f"{'商品名称':<12} {'原价(元)':<10} {'数量':<5} {'折扣价(元)':<8} {'小计(元)':<10}")
    print("-" * 60)

    total_original = 0.0  # 原价总计
    total_paid = 0.0  # 实付总计
    total_quantity = 0  # 商品总数量

    for item in shopping_cart:
        name, original_price, quantity, discount_price = item
        subtotal = discount_price * quantity
        total_original += original_price * quantity
        total_paid += subtotal
        total_quantity += quantity
        print(f"{name:<14} {original_price:<10.2f} {quantity:<5} {discount_price:<10.2f} {subtotal:<10.2f}")

    print("-" * 60)
    print(f"商品总数: {total_quantity} 件")
    print(f"原价总计: ¥{total_original:.2f}")
    print(f"优惠金额: ¥{total_original - total_paid:.2f}")
    print(f"实付金额: ¥{total_paid:.2f}")
    print(f"账户余额: ¥{user_money:.2f}")
    print("=" * 60)
    print("感谢您的光临，祝您购物愉快，欢迎下次再来！😊")


if __name__ == "__main__":
    main()
